package com.wiwj.auth;

import cn.hutool.crypto.SecureUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hive.service.auth.PasswdAuthenticationProvider;

import javax.security.sasl.AuthenticationException;

public class DefaultAuthPolicy implements PasswdAuthenticationProvider, Configurable {

    private static final Log LOG = LogFactory.getLog(DefaultAuthPolicy.class);
    private static final String HIVE_JDBC_PASSWD_AUTH_PREFIX = "hive.jdbc.passwd.auth.%s";
    private Configuration conf = null;

    public DefaultAuthPolicy() {

    }

    @Override
    public void Authenticate(String inputUser, String inputPassword) throws AuthenticationException {
        LOG.info("用户：" + inputUser + " 尝试登录");
        String confPassword = conf.get(String.format(HIVE_JDBC_PASSWD_AUTH_PREFIX, inputUser));
        if (confPassword == null) {
            String message = "用户：" + inputUser + " 不存在";
            LOG.info(message);
            throw new AuthenticationException(message);
        }
        String md5Password = SecureUtil.md5(inputPassword);
        if (!md5Password.equals(confPassword)) {
            String message = "用户：" + inputUser + " 密码输入错误";
            throw new AuthenticationException(message);
        }
        LOG.info("用户: " + inputUser + " 登录成功");
    }

    @Override
    public void setConf(Configuration configuration) {
        this.conf = configuration;
    }

    @Override
    public Configuration getConf() {
        if (conf == null) {
            this.conf = new Configuration();
        }
        return conf;
    }
}
